// 封装 axios
import axios from "axios";
import router from "@/router";
import store from '@/store/index';
import { Message, Notification, Loading } from 'element-ui';

const service = axios.create({
    baseURL: (process.env.VUE_APP_MODE === 'development') ? '/napi' : (process.env.VUE_APP_BASE_API + process.env.VUE_APP_API_BASE_URL),
    timeout: 10000
})
let loading = null;
//请求拦截器
service.interceptors.request.use(config => {
    //在发送请求前添加loading
    loading = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
    })
    const { token } = store.state;
    if (token) {
        config.headers['Authorization'] = "Bearer" + token;
    } else {
        router.push({
            path: '/login'
        })
    }
    if (config.method === 'get') {
        config.params = {
            ...config.params,
            t: new Date().getTime(), //添加时间戳
        }
        config.headers['Content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    } else {
        config.data = {
            ...config.data,
            t: new Date().getTime(), //添加时间戳
        }
        config.headers['Content-type'] = 'application/json;charset=UTF-8'
    }
    return config;
}, (error) => {
    return Promise.reject(error);
})

//响应拦截器
service.interceptors.response.use(response => {
    //关闭loading
    loading.close();
    if (response.status === 200) { //请求成功
        return Promise.resolve(response.data);  //mock数据时，模拟不了code 200，后续再修订~~~~~~(使用mock服务)
        // if (response.data.code === 200) {
        //     return Promise.resolve(response.data);
        // } else {
        //     //错误提示 
        //     Message({
        //         showClose: true,
        //         message: response.data.msg,
        //         type: 'error'
        //     });
        //     return Promise.reject(response);
        // }
    } else {
        return Promise.reject(response);
    }
}, error => {
    console.log('error:',error);
    loading.close();
    if (error.response && error.response.status) {
        const status = error.response.status;
        let message = '';
        switch (status) {
            case 400:
                message = '请求错误';
                break;
            case 401: //未登录、登录过期
                message = '身份验证错误，请重新登录';
                localStorage.removeItem('token');
                store.commit('setToken', null);
                // 未登录则跳转到登录页面，并携带当前页面的路径,在登录成功后返回当前页面
                router.replace({
                    path: '/login',
                    query: {
                        redirect: router.currentRoute.fullPath
                    }
                })
                break;
            case 403:
                message = '没有访问权限';
                //跳转登录页，并将要浏览的页面fullPath传过去，登录成功后跳转
                setTimeout(() => {
                    router.replace({
                        path: '/login',
                        query: {
                            redirect: router.currentRoute.fullPath
                        }
                    })
                }, 1000);
                break;
            case 404:
                message = '请求地址出错';
                break;
            case 408:
                message = '请求超时';
                break;
            case 500:
                message = '服务器内部错误';
                break;
            case 501:
                message = '服务未实现';
                break;
            case 502:
                message = '网管错误';
                break;
            case 503:
                message = '服务不可用';
                break;
            case 504:
                message = '网关超时';
                break;
            case 505:
                message = 'HTTP版本不受支持';
                break;
            default:
                message = '请求失败'
        }
        Notification({
            title: '提示',
            message: message || error.response.data.message || error.message,
            position: 'top-right'
        })
        return Promise.reject(error);
    }
    return Promise.reject(error);
})
export { service as axios }